package novel.mzx.com.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.gyf.immersionbar.ImmersionBar;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;

import butterknife.BindView;
import novel.mzx.com.R;
import novel.mzx.com.adapter.CommentAdapter;
import novel.mzx.com.base.BaseActivity;
import novel.mzx.com.bean.CommentBean;
import novel.mzx.com.http.Api;
import novel.mzx.com.http.SpDataUtils;
import novel.mzx.com.utils.JSONUtils;
import novel.mzx.com.utils.SPUtil;
import novel.mzx.com.utils.ToastUtils;
import novel.mzx.com.views.ExpandTextView;
import novel.mzx.com.views.RoundImageView;
import novel.mzx.com.views.XCRoundImageView;

/**
 * 展示评论页面：
 *      * 使用了recyclerView控件来展示所有评论文章信息。
 * */
public class CircleDetailsActivity extends BaseActivity {

    // 快速获取页面控件
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    @BindView(R.id.iv_delete)
    ImageView iv_delete;
    @BindView(R.id.tv_add)
    TextView tv_add;
    @BindView(R.id.nick_tv)
    TextView nick_tv;
    @BindView(R.id.time_tv)
    TextView time_tv;
    @BindView(R.id.expand_tv)
    ExpandTextView expand_tv;
    @BindView(R.id.one_image_fl)
    FrameLayout one_image_fl;
    @BindView(R.id.one_image_iv)
    RoundImageView one_image_iv;
    @BindView(R.id.iv_play)
    ImageView iv_play;
    @BindView(R.id.head_iv)
    XCRoundImageView head_iv;
    @BindView(R.id.comment_tv)
    TextView comment_tv;

    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.tv_friend)
    TextView tv_friend;
    @BindView(R.id.position_tv)
    TextView position_tv;
    @BindView(R.id.iv_zan)
    ImageView iv_zan;
    private LinearLayoutManager mLinearLayoutManager;

    private CommentAdapter adapter;
    // 定义各个字段
    String id;
    String nickName;
    String account;
    String logo;
    String address;
    @Override
    protected int getResourceId() {
        return R.layout.activity_circle_details;
    }

    @Override
    protected void initView() {
        super.initView();

        // 构建日期格式字段
        ImmersionBar.with(this).titleBar(R.id.toolbar).keyboardEnable(true).init();
        ImmersionBar.with(this).keyboardEnable(false).statusBarDarkFont(true, 0.2f).navigationBarColor(R.color.btn3).init();

        // 实现返回按钮逻辑
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        // 修改布局管理的一些属性
        mLinearLayoutManager = new LinearLayoutManager(this, LinearLayout.VERTICAL,false);
        recyclerView.setLayoutManager(mLinearLayoutManager);
        recyclerView.setNestedScrollingEnabled(false);


        // 获取intent中的一些额外数据并将数据传入到 id 等变量中
        id = getIntent().getStringExtra("id");
        logo = getIntent().getStringExtra("logo");
        nickName = getIntent().getStringExtra("nickName");
        String imageUrl = getIntent().getStringExtra("imageUrl");
        String content = getIntent().getStringExtra("content");
        String time = getIntent().getStringExtra("time");
        String commentSize = getIntent().getStringExtra("commentSize");
        account = getIntent().getStringExtra("account");
        address = getIntent().getStringExtra("address");

        if(null != address){
            position_tv.setText(address);
        }

        String loginAccount = SPUtil.getInstance().getString("account", "");
        if(loginAccount.equals(account)){//如果登录帐号与发布人帐号一样 则不显示添加好友按钮
            tv_friend.setVisibility(View.GONE);
        }


        nick_tv.setText(nickName);
        time_tv.setText(time);
        expand_tv.setText(content);
        comment_tv.setText(commentSize);


        if(account.equals(SpDataUtils.getAccount())){//如果是同一个人发布的 显示删除按钮
            iv_delete.setVisibility(View.VISIBLE);
        }else {
            iv_delete.setVisibility(View.GONE);
        }

        // 调用本地图片作为 显示头像的图片
        Glide.with(this).load(Api.mainImgHost+logo).asBitmap().into(head_iv);

        if(null != imageUrl){
            if(!imageUrl.endsWith("mp4")){
                one_image_fl.setVisibility(View.VISIBLE);
                one_image_iv.setVisibility(View.VISIBLE);
                iv_play.setVisibility(View.GONE);
                Glide.with(this).load(Api.mainImgHost+imageUrl).into(one_image_iv);
            }else {
                one_image_fl.setVisibility(View.GONE);
                one_image_iv.setVisibility(View.GONE);
                iv_play.setVisibility(View.VISIBLE);
                Bitmap videoThumbnail = createVideoThumbnail(Api.mainImgHost + imageUrl, MediaStore.Images.Thumbnails.MINI_KIND);
                one_image_iv.setImageBitmap(videoThumbnail);
            }
        }

        getData();

        registerBoradcastReceiver();

        // 点击评价按钮自动跳转页面
        tv_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(CircleDetailsActivity.this, AddCommentActivity.class);
                intent.putExtra("id",id+"");
                startActivity(intent);
            }
        });

        // 删除评论的逻辑
        iv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OkGo.<String>post(Api.mainHost+Api.deleteCircleInfoUrl)
                        .params("jzCircleId",id)
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {
                                Log.e("删除",response.body());

                                CommentBean commentBean = JSONUtils.parserObject(response.body(),CommentBean.class);
                                int code = commentBean.getResultCode();
                                if(code == 200){
                                    Intent intent = new Intent();
                                    intent.setAction("freshCircle");
                                    sendBroadcast(intent);
                                    finish();
                                }else {

                                }
                            }

                            @Override
                            public void onError(Response<String> response) {
                                super.onError(response);

                            }
                        });
            }
        });

        // 添加好友的逻辑
        tv_friend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });


    }

    // 注册广播
    public void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction("refreshComment");
        //注册广播
        registerReceiver(broadcastReceiver, myIntentFilter);
    }

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(action.equals("refreshComment")){
                // 接受广播调用方法
                getData();
            }
        }
    };

    // 接受广播后的逻辑 ———— 添加好友
    private void getData() {
        OkGo.<String>post(Api.mainHost+Api.listByCircleIdAndCommentStateInfoUrl)
                .params("commentCircleId",id)
                .params("commentState","同意")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Log.e("评价列表",response.body());

                        CommentBean commentBean = JSONUtils.parserObject(response.body(),CommentBean.class);
                        int code = commentBean.getResultCode();
                        if(code == 200){
                            List<CommentBean.Data> data = commentBean.getData();
                            adapter = new CommentAdapter(CircleDetailsActivity.this,R.layout.list_item_comment,data);
                            recyclerView.setAdapter(adapter);
                            comment_tv.setText(data.size()+"");
                        }else {

                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);

                    }
                });
    }


    // 将图片压缩到可以作为头像显示的逻辑
    public static Bitmap createVideoThumbnail(String filePath, int kind)
    {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try
        {
            if (filePath.startsWith("http://")
                    || filePath.startsWith("https://")
                    || filePath.startsWith("widevine://"))
            {
                retriever.setDataSource(filePath, new Hashtable<String, String>());
            }
            else
            {
                retriever.setDataSource(filePath);
            }
            bitmap = retriever.getFrameAtTime(0, MediaMetadataRetriever.OPTION_CLOSEST_SYNC); //retriever.getFrameAtTime(-1);
        }
        catch (IllegalArgumentException ex)
        {
            // Assume this is a corrupt video file
            ex.printStackTrace();
        }
        catch (RuntimeException ex)
        {
            // Assume this is a corrupt video file.
            ex.printStackTrace();
        }
        finally
        {
            try
            {
                retriever.release();
            }
            catch (RuntimeException ex)
            {
                // Ignore failures while cleaning up.
                ex.printStackTrace();
            }
        }

        if (bitmap == null)
        {
            return null;
        }

        if (kind == MediaStore.Images.Thumbnails.MINI_KIND)
        {//压缩图片 开始处
            // Scale down the bitmap if it's too large.
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            int max = Math.max(width, height);
            if (max > 512)
            {
                float scale = 512f / max;
                int w = Math.round(scale * width);
                int h = Math.round(scale * height);
                bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true);
            }//压缩图片 结束处
        }
        else if (kind == MediaStore.Images.Thumbnails.MICRO_KIND)
        {
            bitmap = ThumbnailUtils.extractThumbnail(bitmap,
                    96,
                    96,
                    ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        }
        return bitmap;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (broadcastReceiver != null) {
            unregisterReceiver(broadcastReceiver);
        }
    }
}
